package com.dk.filter;

import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private RedisTemplate redisTemplate;

//    过滤器的类型
//    pre   路由之前过滤
//    routing  路由之时过滤
//    post  路由之后过滤
//    error  出现错误之后过滤
    @Override
    public String filterType() {
        return "pre";
    }

//    过滤器的顺序   从小到大 正序
    @Override
    public int filterOrder() {
        return 0;
    }

//    过滤器的开关  true 打开
    @Override
    public boolean shouldFilter() {
        return true;
    }

//    过滤功能
    @Override
    public Object run() throws ZuulException {
        //获取当前线程请求上下文类
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request域对象
        HttpServletRequest request = currentContext.getRequest();
        //获取参数
        String token = request.getHeader("token");
        if(token == null){
            //设置响应域对象
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(400);
            //获取response
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                Result result = Result.buildResult(ResultEnum.NOLOGIN).setResult("用户未登录，无法访问服务,请先登录");
                response.getWriter().write(objectMapper.writeValueAsString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        从redis 中获取数据
        Object user = redisTemplate.boundValueOps(token).get();
        //校验用户名是否存在，如果不存在，说明用户未登录，不放过
        if(user == null ){
            //设置响应域对象
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(400);
            //获取response
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                Result result = Result.buildResult(ResultEnum.NOLOGIN).setResult("用户未登录，无法访问服务,请先登录");

                response.getWriter().write(objectMapper.writeValueAsString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
